package br.unisul.sintatico;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Date;

import javax.swing.JOptionPane;

class GetResourceAsStream {

	public String getText(String caminho) {
		String text = "";
		
		try {
			
			InputStream is = getClass().getResourceAsStream(caminho);

			if (is == null) {
				System.err.println("JAR File not found in JAR at: " +caminho);
				return "";
			}

			InputStreamReader isr = new InputStreamReader(is);
			StringBuffer sb = new StringBuffer();

			char[] b = new char[8192];
			int n;
			while ((n = isr.read(b)) > 0){
				sb.append(b, 0, n);
			}

			text = sb.toString();

		} catch (IOException e) {
			System.err.println("IOEXCEPTION ON JAR File not found in JAR at: " +caminho);
		}

		return text;
	}
	
	public File getFile(String caminho) {
		File f = new File(System.getProperty("java.io.tmpdir")+"/tmp"+new Date().getTime()+".LMS");
		
		InputStream inputStream;
		
		try {
			inputStream = getClass().getResourceAsStream(caminho);
			OutputStream out= new FileOutputStream(f);
			byte buf[]=new byte[1024];
			int len;

			while((len=inputStream.read(buf))>0){
				out.write(buf,0,len);
			}

			out.close();
			inputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			f.createNewFile();
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		System.out.println(f.length());
		JOptionPane.showMessageDialog(null,f.getAbsolutePath());
		
		return f;

	}
	


	public static void main(String[] args) throws IOException {
		GetResourceAsStream ts = new GetResourceAsStream();
		System.out.println(ts.getText("/gramatica.bak"));
	}
}
